//
//  PublicVC.m
//  Graduate
//
//  Created by xp on 16/8/2.
//  Copyright © 2016年 mingthink. All rights reserved.
//

#import "PublicVC.h"
#import "SVProgressHUD.h"
#import "SBMember.h"
//#import "BaiduMobStat.h"
#import "LoginVC.h"
@interface PublicVC ()

@end

@implementation PublicVC

- (void)viewDidLoad {
    [super viewDidLoad];
     DeLog(@"------currentVC:%@",self);
    self.view.backgroundColor = GET_HEX_COLOR(TABLE_SEPARATOR_CONTENT);
    self.navigationController.interactivePopGestureRecognizer.delegate=nil;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [self initNavigationView];
    [self createTitle];
    
    if (IOS_VER > 7.0) {
        self.automaticallyAdjustsScrollViewInsets = false;
    }

    //self.isNetwork = true;//默认为有网络
}
-(void)requestErrorNotice:(NSNotification*)notice{
    DeLog(@"------requestErrorNotice:%@",[notice object]);
    DeLog(@"------FailInfo:%@",notice.userInfo);
    [self stopWait];
    [self stopAnimating];
    NSInteger code = [[notice.userInfo objectForKey:kResCode] integerValue];
    DeLog(@"---------errorCode：%ld",code);
    switch (code) {
            case RRCTokenExpire: case RRCTokenInvalid:case RRCLongDistanceLogIn:case RRCForcedLogout:case RRCSystemMaintenance:{
                [EMAlertView showAlertWithTitle:@"提示" message:@"您的登录已过期，请重新登录" completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
                    AppDelegate *app=(AppDelegate *)[UIApplication sharedApplication].delegate;
                    app.loginMember = nil;
                    MemberService *memberService = [[MemberService alloc] init];
                    [memberService logout];
                    [app goLogin];
                } cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
            break;
        }
           case RRCFailed:
            //[WToast showWithText:notice.userInfo[@"Message"]];
            [self.view makeToast:notice.userInfo[@"Message"]];
            break;
            
//        case RRCTokenExpire:{
//            //token正常过期去请求刷新token的接口
//            break;
//        }
            
        default:
            if (![StringUtils isEmpty:notice.userInfo[@"Message"]]) [self.view makeToast:notice.userInfo[@"Message"]];
            break;
    }
}

- (void)initNavigationView{
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVW, NAVBAR_HEIGH)];
    self.navView.backgroundColor = GET_HEX_COLOR(NAVBAR_BG_COLOR);
    [self.view addSubview:self.navView];
    
//    UIView *view_separateLine = UIView.new;
//    view_separateLine.tag = 110;
//    [self.navView addSubview:view_separateLine];
//    view_separateLine.backgroundColor = GET_HEX_COLOR(TABLE_SEPARATOR_GRAY);
//    view_separateLine.layer.shadowColor = GET_HEX_COLOR(TABLE_SEPARATOR_GRAY).CGColor;//shadowColor阴影颜色
//    view_separateLine.layer.shadowOffset = CGSizeMake(0,1);//shadowOffset阴影偏移,x向右偏移0，y向下偏移4
//    view_separateLine.layer.shadowOpacity = 0.9;//阴影透明度，默认0
//    view_separateLine.layer.shadowRadius = 1;
//    view_separateLine.sd_layout.bottomSpaceToView(self.navView,0).leftEqualToView(self.navView).rightEqualToView(self.navView).heightIs(0.5);
    //self.view_line = view_line;

}
-(void)createTitle {
    int titleW = DEVW - 100;
    int titleX = (DEVW - titleW)/2;
    int titleY = STATUS_HEIGH;
    int titleH = NAVBAR_HEIGH - titleY;
    _navTitleL = [[UILabel alloc]initWithFrame:CGRectMake(titleX, titleY, titleW, titleH)];
    _navTitleL.font = [UIFont boldSystemFontOfSize:TEXT_FONT_36];
    _navTitleL.text = self.titleName;
    _navTitleL.textColor =[UIColor whiteColor];
    _navTitleL.textAlignment = NSTextAlignmentCenter;
    [self.navView addSubview:_navTitleL];
}
-(void)setTitle:(NSString *)titleName {
    _titleName=titleName;
    _navTitleL.text=titleName;
}

-(void)showWaitWithTitle:(NSString *)title{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];//背景能点击
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setCornerRadius:6];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];//圆圈图形
    [SVProgressHUD showWithStatus:title];
}
-(void)stopWait{
    [SVProgressHUD dismiss];
}

//- (void)checkOutTheInternet
//{
//    WEAK_SELF(self);
//    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        switch (status) {
//                //            case AFNetworkReachabilityStatusUnknown:
//                //                DeLog(@"未识别的网络");
//                //                break;
//
//            case AFNetworkReachabilityStatusNotReachable:
//                [weakSelf showErrorType:ErrorTypeNetwork superView:weakSelf.view x:0 offsetY:-30 newViewTag:TIPS_VIEW_TAG];
//                [WToast showWithText:@"貌似没有网络请检查您的网络连接"];
//                weakSelf.isNetwork = false;
//                break;
//
//              case AFNetworkReachabilityStatusReachableViaWWAN:
//                weakSelf.isNetwork = true;
//                [weakSelf errorButtonClick:nil];
//                //if (!weakSelf.isNetwork) [weakSelf errorV:weakSelf.navigationController.viewControllers];
//                break;
//                                DeLog(@"2G,3G,4G...的网络");
//                                break;
//
//            case AFNetworkReachabilityStatusReachableViaWiFi:
//                weakSelf.isNetwork = true;
//                [weakSelf errorButtonClick:nil];
//                //if (!weakSelf.isNetwork) [weakSelf errorV:weakSelf.navigationController.viewControllers];
//                break;
//                                DeLog(@"wifi的网络");
//                                break;
//
//    //default:
////                weakSelf.isNetwork = true;
////                [weakSelf errorButtonClick:nil];
////                //if (!weakSelf.isNetwork) [weakSelf errorV:weakSelf.navigationController.viewControllers];
//                //break;
//        }
//    }];
//    [manager startMonitoring];
//}

//移除无网络页面
-(void)errorV:(NSArray*)vcs{
    [vcs enumerateObjectsUsingBlock:^(PublicVC *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [[obj.view viewWithTag:TIPS_VIEW_TAG] removeFromSuperview];
        if ([obj isKindOfClass:UITabBarController.class]){
            UITabBarController *tabVCS = (UITabBarController*)obj;
            [self errorV:tabVCS.viewControllers];
        }else{
            if (!obj.isNetwork){
                [obj errorButtonClick:nil];
            }
            obj.isNetwork = true;
        }
    }];
}

//-(BOOL)errorButtonClick:(UIButton *)sender{
//    if (self.isNetwork) [[self.view viewWithTag:TIPS_VIEW_TAG] removeFromSuperview];
//    return false;
//}

-(void)showErrorType:(ErrorTypeTips)type superView:(UIView *)targetView x:(float)x offsetY:(float)offsetY newViewTag:(NSInteger)viewTag{
    if ([targetView viewWithTag:viewTag]) {
        return;
    }
    
    NSArray *errorDataAry = @[@[@"no_content_tip",@"貌似没有网络",@"刷新试试"]
                              ,@[@"no_content2",@"暂无内容",@"返回上一页"]];
    
    UIView *centerView = [[UIView alloc]initWithFrame:CGRectMake(x, 0, targetView.frame.size.width, targetView.frame.size.height)];
    [centerView setBackgroundColor:[UIColor whiteColor]];
    [centerView setTag:viewTag];
    [targetView addSubview:centerView];
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, 180, 180)];
    img.contentMode = UIViewContentModeScaleAspectFit;
    [centerView addSubview:img];
    [img setImage:[UIImage imageNamed:errorDataAry[type][0]]];
    img.center = CGPointMake(centerView.center.x - x, centerView.center.y + offsetY);
    
    UILabel *lab_detail = UILabel.new;
    [centerView addSubview:lab_detail];
    lab_detail.textAlignment = NSTextAlignmentCenter;
    lab_detail.text = errorDataAry[type][1];
    lab_detail.font = GET_SYSTEM_FONT(TEXT_FONT_32);
    lab_detail.textColor = GET_HEX_COLOR(TEXT_DEEP_GRAY);
    lab_detail.sd_layout.topSpaceToView(img,0).leftSpaceToView(centerView,0).rightSpaceToView(centerView,0).autoHeightRatio(0);
    
    UIButton *exampleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [centerView addSubview:exampleBtn];
    [exampleBtn setTitle:errorDataAry[type][2] forState:UIControlStateNormal];
    exampleBtn.titleLabel.font = GET_SYSTEM_FONT(TEXT_FONT_32);
    [exampleBtn setTitleColor:GET_HEX_COLOR(CELL_LABLE_BORDER_RED) forState:UIControlStateNormal];
    exampleBtn.layer.borderWidth = 1;
    exampleBtn.layer.cornerRadius = 8.0f;
    exampleBtn.tag = type;
    exampleBtn.layer.borderColor = GET_HEX_COLOR(CELL_LABLE_BORDER_RED).CGColor;
    [exampleBtn addTarget:self action:@selector(errorButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    exampleBtn.sd_layout.topSpaceToView(lab_detail,20).centerXEqualToView(centerView).widthIs(110).heightIs(40);
    
    [self.view bringSubviewToFront:self.navView];
}

-(void)startAnimatingWithWebViewFrame:(CGRect)webViewFrame
{
    if (!spinner) {
        alf = [[UIView alloc]initWithFrame:webViewFrame];
        alf.backgroundColor =GET_RGB_COLOR(150, 150, 150, 0.3);
        
        int spinnerW = 50;
        int spinnerH = 50;
//        int spinnerX = (alf1.width - spinnerW)/2;
//        int spinnerY = (alf1.height - spinnerH)/2;
        spinner = [[TKLoadingAnimationView alloc] initWithFrame:CGRectMake(0, 0, spinnerW, spinnerH) tkLoadingAnimationViewStyle:1];

        //spinner.center = [alf1 convertPoint:alf1.center fromView:alf1.superview];
        NSMutableArray *imageArr=[[NSMutableArray alloc]init];
        for (int i=1; i<=12; i++) {
            UIImage *image=[UIImage imageNamed:[NSString stringWithFormat:@"network_loading_%d",i]];
            [imageArr addObject:image];
        }
        spinner.gifs=imageArr;
        
//        if (isFullScreen) {
//            //alf1.frame = CGRectMake(0, 0, DEVW, DEVH-NAVBAR_HEIGH);
//            
//            spinnerY = (DEVH - NAVBAR_HEIGH - 40 - spinnerH)/2;
//            spinner.frame = CGRectMake(spinnerX, spinnerY, spinnerW, spinnerH);
//        }

        //spinner.center = self.view.center;
//        //alf.alpha = 0.3;
//
//        alf1.hidden=YES;
        [self.view addSubview:alf];
        [alf addSubview:spinner];

    }
    alf.hidden=NO;
    alf.frame=webViewFrame;
    spinner.center = [alf convertPoint:alf.center fromView:alf.superview];
    [spinner startAnimating];
}
-(void)stopAnimating
{
    [spinner stopAnimating];
    alf.hidden=YES;
}
// 哪些页面支持自动转屏
- (BOOL)shouldAutorotate{
    return NO;
}

//当前viewcontroller支持哪些转屏方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    DeLog(@"控制器销毁");
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestErrorNotice:) name:REQUEST_ERROR_NOTICE object:nil];
    //[[BaiduMobStat defaultStat] pageviewStartWithName:NSStringFromClass(self.class)];
    //[self checkOutTheInternet];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:REQUEST_ERROR_NOTICE object:nil];
    //[[BaiduMobStat defaultStat] pageviewEndWithName:NSStringFromClass(self.class)];
}

@end
